package com.example.tamplate.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.tamplate.model.Admin;
import com.example.tamplate.model.vo.Result;
import com.example.tamplate.service.impl.AdminServiceImpl;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

@CrossOrigin
@RequestMapping("/admin")
@Api(tags = "管理员")
@RestController
public class AdminController {

    @Autowired
    public AdminServiceImpl adminService;

    @Value("${jwt.secret}")
    private String jwtSecret; // 从配置文件中获取JWT密钥


    @ApiOperation("管理员登录")
    @PostMapping("/login")
    public Result login(@RequestBody Admin admin) {
        // 根据用户名查询管理员信息
        String username = admin.getUsername();
        String password = admin.getPassword();
        QueryWrapper<Admin> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        Admin one = adminService.getOne(wrapper);

        // 验证管理员是否存在
        if (one != null) {
            // 验证密码是否正确
            if (one.getPassword().equals(password)) {
                String token = generateToken(one);
                // 登录成功，将token设置到返回结果中
                one.setToken(token); // 假设Admin类有一个setToken方法
                return Result.success(one);
            } else {
                // 密码错误
                return Result.fail("密码错误");
            }
        } else {
            // 用户名不存在
            return Result.fail("用户名不存在");
        }
    }


    @ApiOperation("添加")
    @PostMapping("/add")
    public Result addAdmin(@RequestBody Admin admin) {
        adminService.save(admin);
        return Result.success(admin);
    }

    @ApiOperation("查询")
    @GetMapping("/list")
    public Result listAdmin() {
        return Result.success(adminService.list());
    }

    // 生成JWT token
    private String generateToken(Admin admin) {
        Claims claims = Jwts.claims().setSubject(admin.getUsername());
        // 可以添加自定义的payload内容
        // claims.put("role", "admin");

        return Jwts.builder()
                .setClaims(claims)
                .signWith(SignatureAlgorithm.HS256, jwtSecret)
                .compact();
    }

}

